package com.sunwhite.herostore.msg.util;

import com.google.protobuf.GeneratedMessageV3;
import com.sunwhite.herostore.common.GameMsgRecognizer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * protocol消息编码处理器
 */
public class GameMsgEncode extends ChannelOutboundHandlerAdapter {
    public static final Logger LOGGER= LoggerFactory.getLogger(GameMsgEncode.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(null!=msg&&!(msg instanceof GeneratedMessageV3)){
            super.write(ctx, msg, promise);
            return;
        }
        int msgCode= GameMsgRecognizer.getMsgCodeByMsgClass(msg.getClass());
        if (msgCode<0){
            return;
        }
        byte[] msgBody = ((GeneratedMessageV3) msg).toByteArray();

        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeShort((short)0);        //放入消息长度
        buffer.writeShort((short)msgCode);  //放入消息编号
        buffer.writeBytes(msgBody); //写入消息体

        BinaryWebSocketFrame binaryWebSocketFrame = new BinaryWebSocketFrame(buffer);
        super.write(ctx,binaryWebSocketFrame,promise);

    }
}
